<template>
    <view class="canvas-container">
        <canvas class="mycanvas" canvas-id="mycanvas" :disable-scroll="true" @touchstart="touchstart"
            @touchmove="touchmove" @touchend="touchend"></canvas>
        <view class="button-group">
            <button class="one" @click="clear">清空</button>
            <button class="one" @click="changeTool('pen')">笔刷</button>
            <button class="one" @click="changeTool('eraser')">橡皮擦</button>
            <button class="one" @click="undo">撤销</button>
            <button class="two" @click="finish">确定</button>
        </view>
    </view>
</template>

<script setup>
import { reactive, onMounted } from "vue";
import {
    onReachBottom,
    onShow, onLoad, onReady, onHide
} from '@dcloudio/uni-app';

const props = defineProps({
})
const emits = defineEmits()
const data = reactive({
    ctx: null, //绘图图像
    points: [],//路径点集合


    imgHistory:[],      //历史记录
    undoIndex:0,        //撤销步数

    currMode: 'pen', //当前绘图模式
})

onReady(() => {

    data.ctx = uni.createCanvasContext("mycanvas", this);   //创建绘图对象

})

// 切换工具
const changeTool = (name) =>{
    data.currMode = name;
}

//触摸开始，获取到起点
const touchstart = (e) => {

    if(data.currMode == 'default')return
    let startX = e.changedTouches[0].x;
    let startY = e.changedTouches[0].y;


    switch (data.currMode) {
        case 'pen':
            //设置画笔样式
            data.ctx.lineWidth = 20;
            data.ctx.lineCap = "round"
            data.ctx.lineJoin = "round"

            // 设置画笔颜色
            data.ctx.strokeStyle = "#ff0000"; // 设置为红色

            // 如果切换回绘制模式
            data.ctx.globalCompositeOperation = 'source-over'; // 恢复默认绘制效果
            let startPoint = { X: startX, Y: startY };

            /* **************************************************
                #由于uni对canvas的实现有所不同，这里需要把起点存起来
            * **************************************************/
            data.points.push(startPoint);

            //每次触摸开始，开启新的路径
            data.ctx.beginPath();
            break;
        case 'eraser':
            // 如果切换到橡皮擦模式
            data.ctx.globalCompositeOperation = 'destination-out'; // 设置橡皮擦效果
            data.ctx.beginPath();
            // data.ctx.arc(startX, startX, 10, 0, Math.PI * 2);
            data.ctx.fill();
            data.ctx.closePath();
            break;
    }
}

//触摸移动，获取到路径点
const touchmove = (e) => {
    if(data.currMode == 'default')return

    let moveX = e.changedTouches[0].x;
    let moveY = e.changedTouches[0].y;
    let movePoint = { X: moveX, Y: moveY };
    data.points.push(movePoint);//存点
    let len = data.points.length;
    if (len >= 2) {
        draw();//绘制路径
    }

}

// 触摸结束，将未绘制的点清空防止对后续路径产生干扰
const touchend = () => {
    if(data.currMode == 'default')return

    data.points = [];
    finish()
}

//绘制笔迹
/**
 * 1.为保证笔迹实时显示，必须在移动的同时绘制笔迹
 * 2.为保证笔迹连续，每次从路径集合中区两个点作为起点（moveTo）和终点(lineTo)
 * 3.将上一次的终点作为下一次绘制的起点（即清除第一个点）
 */
const draw = () => {
    let point1 = data.points[0]
    let point2 = data.points[1]
    data.points.shift()
    data.ctx.moveTo(point1.X, point1.Y)
    data.ctx.lineTo(point2.X, point2.Y)
    data.ctx.stroke()
    data.ctx.draw(true)
}

//清空画布
const clear = () => {
    uni.getSystemInfo({
        success: function (res) {
            let canvasw = res.windowWidth;
            let canvash = res.windowHeight;
            data.ctx.clearRect(0, 0, canvasw, canvash);
            data.ctx.draw(false);
            data.undoIndex = 0;
            data.imgHistory = [];
        }
    })
}

//完成绘画并保存到本地
const finish = () => {
    uni.getSystemInfo({
        success: function (res) {
            let canvasw = res.windowWidth;
            let canvash = res.windowHeight;
            console.log(canvasw, canvash);
            // 此API,H5中返回的是base64,APP中返回的是png图片,一个临时路径
            uni.canvasToTempFilePath({
                canvasId: 'mycanvas',
                fileType: 'png',        // 设置文件类型为 PNG
                quality: 1,             // 设置图片的质量为 1
                width: canvasw,              //画布宽度（默认为canvas宽度-x）
                height: canvash,             //画布高度（默认为canvas高度-y）
                destWidth: canvasw,         //输出图片宽度（默认为 width * 屏幕像素密度）
                destHeight: canvash,        //输出图片高度（默认为 height * 屏幕像素密度）
                success: function (res) {
                    let path = res.tempFilePath;
                    data.imgHistory.push(path)
                    data.undoIndex = data.imgHistory.length-1;
                }
            })
        }
    })

}


//撤销上一步
const undo = () => {

    console.log(data.currMode.value);

    if(data.imgHistory.length < 1){
        clear()
        return
    }

    let lastImg = data.imgHistory[data.undoIndex-1]  // 取出倒数第二步的画布状态
    data.undoIndex--            //更新撤销步数
    let context = uni.createCanvasContext("mycanvas", this);

    if(lastImg){
        context.drawImage(lastImg, 0, 0);  // 将倒数第二步的画布状态绘制到画布上
    }

    context.draw();

    data.imgHistory.pop()  // 删除最后一步的画布状态

}


</script>


<style scoped lang="scss">
.canvas-container {
    overflow: hidden;
    background: #fff;
}

.button-group {
    position: fixed;
    left: 50rpx;
    bottom: 10rpx;
    display: flex;
    align-items: center;

    .one {
        width: 100rpx;
        margin-right: 50rpx;
        border: 1px solid #123454;
    }

    .two {
        width: 100rpx;
        background-color: #123454;
        color: #fff;
    }
}

.mycanvas {
    width: 100%;
    height: calc(100vh - var(--window-top));
    background-color: #ECECEC;
}

.footer {
    font-size: 16px;
    height: 150upx;
    display: flex;
    justify-content: space-around;
    align-items: center;
}

.left,
.right {
    line-height: 100upx;
    height: 100upx;
    width: 250upx;
    text-align: center;
    font-weight: bold;
    color: white;
    border-radius: 5upx;
}

.left {
    background: #007AFF;
}

.right {
    background: orange;
}
</style>